var React = require('react');
var token = $.cookie('token');
var mytoken = JSON.parse(token);
const UserManagement = React.createClass({
    getInitialState: function () {
        return {users: [], roles: []}
    },
    componentWillMount: function () {
        var _this = this;
        $.ajax({
            type: "GET",
            url: "/api/Employee/GetAllEmployeeUser",
            headers: {
                Authorization: "Bearer " + mytoken.access_token
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                _this.setState({users: data})
            },
            error: function (msg) {
                alert(msg);
            }
        });
        $.ajax({
            type: "GET",
            url: "/api/Employee/GetRoles",
            headers: {
                Authorization: "Bearer " + mytoken.access_token
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                _this.setState({roles: data})
            },
            error: function (msg) {
                alert(msg);
            }
        });
    },
    componentDidMount: function () {
        var _this = this;
        var zTreeObj;
        // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
        var setting = {
            check: {
                enable: true
            }
        };
        // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
        var zNodes = [
            {
                name: "商品中心",
                open: true,
                children: [
                    {
                        id: 4,
                        name: "商品上下架"
                    }, {
                        id: 5,
                        name: "商品信息修改"
                    }
                ]
            }, {
                name: "角色中心",
                open: true,
                children: [
                    {
                        id: 9,
                        name: "角色管理"
                    }, {
                        id: 11,
                        name: "用户管理"
                    },{
                        id:14,
                        name:"操作日志查看"
                    }
                ]
            }, {
                name: "广告中心",
                open: true,
                children: [
                 {
                        id: 12,
                        name: "新品推荐管理"
                    }
                ]
            }, {
                name: "库存中心",
                open: true,
                children: [
                    {
                        id: 6,
                        name: "新货入库"
                    }, {
                        id: 7,
                        name: "退货入库"
                    }, {
                        id: 8,
                        name: "确认发货"
                    }
                ]
            }, {
                name: "订单中心",
                open: true,
                children: [
                    {
                        id: 1,
                        name: "退货处理"
                    }, {
                        id: 2,
                        name: "退款处理"
                    }, {
                        id: 3,
                        name: "商品发货"
                    }
                ]
            }
        ];
        $(document).ready(function () {
            zTreeObj = $
                .fn
                .zTree
                .init($("#treeDemo"), setting, zNodes);
        });

        $('#user-info-submit').click(function () {
            var result = {
                UserRoles: []
            };
            result.UserId = $('#user-id').val();
            result.IsNew = $('#is-new').val();
            result.Account = $('#user-account').val();
            result.NickName = $('#user-nickname').val();
            result.Email = $('#user-email').val();
            result.PhoneNumber = $('#user-phone').val();
            if($("#active-mail").get(0).checked){
                result.IsSendMail ="send";
                alert("send");
            }
            if ($("#random-password").get(0).checked) {
                result.Password = "random"
            } else {
                result.Password = $('#user-password').val();
            }
            _this
                .state
                .roles
                .map(role => {
                    var temp = "#role" + role.RoleId;
                    if ($(temp).is(':checked')) {
                        result
                            .UserRoles
                            .push(role.RoleId);
                    }
                })
            $.ajax({
                type: "Post",
                url: "/api/Employee/AdminChangeUserDetails",
                headers: {
                    Authorization: "Bearer " + mytoken.access_token
                },
                data: result,
                dataType: "json",
                success: function (data) {
                    _this.setState({users: data});
                },
                error: function (msg) {
                    alert("出错了");
                }
            });
        });
        $('#add-user').click(function () {
            $('#is-new').val("new");
            _this
                .state
                .roles
                .map(role => {
                    var temp = "#role" + role.RoleId;
                    if ($(temp).is(':checked')) {
                        $(temp).attr("checked", false);
                    }
                });
            $('#random-password').attr("checked", false);
            $('#random-password').attr("disabled", false);
            $('#user-password').attr("disabled", false);
            $('#user-sure-password').attr("disabled", false);
            $('#active-mail').attr("disabled", false);
            $('#user-account').val("");
            $('#user-nickname').val("");
            $('#user-email').val("");
            $('#user-phone').val("");
            $("#random-password").click(function () {
                $('#random-password').attr("disabled", "disabled");
                $('#user-password').attr("disabled", "disabled");
                $('#user-sure-password').attr("disabled", "disabled");
            });
        });
        $('#user-Permission-submit').click(function () {
            var result = {
                EmployeeId: -1,
                PermissionIdS: []
            }
            result.EmployeeId = $('#user-permission-employeeid').val();
            var zTreeObj = $
                .fn
                .zTree
                .getZTreeObj('treeDemo');
            var nodes = zTreeObj.getCheckedNodes();
            nodes.map(function (node) {
                if (node.children == null) {
                    result
                        .PermissionIdS
                        .push(node.id);
                }
            });
            $.ajax({
                type: "Post",
                url: "/api/Employee/ChangeEmployeePermissions",
                headers: {
                    Authorization: "Bearer " + mytoken.access_token
                },
                data: result,
                dataType: "json",
                success: function (data) {
                    alert(data);
                },
                error: function (msg) {
                    alert("出错了");
                }
            });
        });
    $('#user-delete-submit').click(function(){
        var userId =  $('#user-delete-userid').val();
        alert(userId);
        $.ajax({
                type: "Delete",
                url: "/api/Employee/DeleteEmployeeUser",
                headers: {
                    Authorization: "Bearer " + mytoken.access_token
                },
                data: {
                    "": userId + ""
                },
                dataType: "json",
                success: function (data) {
                    if(data != null){
                        _this.setState({users: data});
                    }else{
                        alert("删除失败")
                    }
                },
                error: function (msg) {
                    alert("出错了");
                }
            });
    });
    },
    setDeleteInfo: function (user) {
        $('#user-delete-userid').val(user.UserId);
        $('#user-delete-username').html (user.NickName);
    },
    //在模态框中设置用户的信息
    setUserInfo: function (user) {
        $('#active-mail').attr("disabled", false);
        $('#is-new').val("");
        $('#user-password').val("");
        $('#user-sure-password').val("");
        $('#user-id').val(user.UserId);
        this
            .state
            .roles
            .map(role => {
                var temp = "#role" + role.RoleId;
                if ($(temp).is(':checked')) {
                    $(temp).attr("checked", false);
                }
            });
        $('#random-password').attr("checked", false);
        $('#random-password').attr("disabled", false);
        $('#user-password').attr("disabled", false);
        $('#user-sure-password').attr("disabled", false);
        $("#random-password").click(function () {
            $('#random-password').attr("disabled", "disabled");
            $('#user-password').attr("disabled", "disabled");
            $('#user-sure-password').attr("disabled", "disabled");
        });
        $('#user-account').val(user.Account);
        $('#user-nickname').val(user.NickName);
        $('#user-email').val(user.Email);
        $('#user-phone').val(user.PhoneNumber);
        if (user.IsActivate == "是") {
            $('#active-mail').attr("disabled", "disabled");
        }

    },
    //在模态框的角色部分获取系统当前的角色
    getRoles: function () {
        return this
            .state
            .roles
            .map(role => {
                return (
                    <div key={role.RoleId} className="checkbox input-lg">
                        <label >
                            <input type="checkbox" id={"role" + role.RoleId}/>{role.Name}
                        </label>
                    </div>
                )
            })
    },
    getUserPermissions: function (user) {
        $('#user-permission-employeeid').val(user.EmployeeId);
        $.ajax({
            type: "GET",
            url: "/api/Employee/GetUserPermissions",
            headers: {
                Authorization: "Bearer " + mytoken.access_token
            },
            contentType: "application/json; charset=utf-8",
            data: {
                "employeeId": user.EmployeeId
            },
            dataType: "json",
            success: function (data) {
                if (data != null) {
                    var zTreeObj = $
                        .fn
                        .zTree
                        .getZTreeObj('treeDemo');
                    data.map(per => {
                        zTreeObj.checkNode(zTreeObj.getNodeByParam("id", per.PermissionId, null), true, true);
                    });
                }
            },
            error: function (msg) {
                alert("权限获取失败");
            }
        });
    },
    //获取所有员工的信息
    getUsers: function () {
        return this
            .state
            .users
            .map(user => {
                return (
                    <tr key={user.UserId}>
                        <td>
                            <li
                                className="dropdown"
                                style={{
                                listStyleType: 'NONE'
                            }}>
                                <a href="#" className="dropdown-toggle" data-toggle="dropdown">
                                    操作
                                    <b className="caret"></b>
                                </a>
                                <ul className="dropdown-menu">
                                    <li>
                                        <a
                                            data-toggle="modal"
                                            data-target="#user-info-modal"
                                            onClick={this
                                            .setUserInfo
                                            .bind(this, user)}>修改</a>
                                    </li>
                                    <li>
                                        <a
                                            data-toggle="modal"
                                            data-target="#user-permission"
                                            onClick={this
                                            .getUserPermissions
                                            .bind(this, user)}>权限</a>
                                    </li>
                                    <li>
                                        <a data-toggle="modal" data-target="#user-delete"  onClick={this
                                            .setDeleteInfo
                                            .bind(this, user)}>删除</a>
                                    </li>
                                </ul>
                            </li>
                        </td>
                        <td>{user.Account}
                        </td>
                        <td>{user.NickName}
                        </td>
                        <td>{user.RoleName}
                        </td>
                        <td>{user.Email}
                        </td>
                        <td>{user.IsActivate}
                        </td>
                        <td>{user.LastLoginTime}
                        </td>
                        <td>{user.LastLoginIpAndAddress}
                        </td>
                        <td>{user.CreateTime}
                        </td>
                    </tr>
                )
            })
    },
    render() {
        return (
            <div>
                <section className="content-header">
                    <h1>
                        角色中心
                        <small>用户管理</small>
                    </h1>
                    <ol className="breadcrumb">
                        <li>
                            <a href="#">
                                <i className="fa fa-dashboard"></i>
                                Stage</a>
                        </li>
                        <li>
                            <a href="#">用户管理</a>
                        </li>
                        <li className="active">概览</li>
                    </ol>
                </section>
                <br/>
                <div className="box">
                    <div className="box-header with-border">
                        <h3 className="box-title">用户管理</h3>
                        <div className="box-tools pull-right">
                            <span className="label label-primary">用户概览</span>
                        </div>
                    </div>
                    <div className="box-body">
                        <table className="table table-striped">
                            <thead>
                                <tr>
                                    <th>操作</th>
                                    <th>账户</th>
                                    <th>昵称</th>
                                    <th>角色</th>
                                    <th>邮箱地址</th>
                                    <th>是否激活</th>
                                    <th>上次登录时间</th>
                                    <th>上次的登录ip和地址</th>
                                    <th>创建时间</th>
                                </tr>
                            </thead>
                            <tbody>
                                {this.getUsers()}
                            </tbody>
                        </table>
                        <button
                            type="button"
                            className="btn btn-primary btn-lg"
                            data-toggle="modal"
                            data-target="#user-info-modal"
                            style={{
                            marginTop: '1%',
                            marginLeft: '90%'
                        }}
                            id="add-user">添加用户</button>
                    </div>
                    <div className="box-footer">
                        <div
                            className="modal fade"
                            id="user-info-modal"
                            tabIndex="-1"
                            role="dialog"
                            aria-labelledby="myModalLabel"
                            aria-hidden="true">
                            <div className="modal-dialog">
                                <div className="modal-content">
                                    <div className="modal-header">
                                        <button type="button" className="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                        <h4 className="modal-title" id="myModalLabel">用户信息</h4>
                                    </div>
                                    <div className="modal-body">
                                        <ul id="myTab" className="nav nav-tabs">
                                            <li className="active">
                                                <a href="#user-info-details" data-toggle="tab">
                                                    用户信息概览</a>
                                            </li>
                                            <li>
                                                <a href="#user-role" data-toggle="tab">角色</a>
                                            </li>
                                        </ul>
                                        <div id="myTabContent" className="tab-content">
                                            <div className="tab-pane fade in active" id="user-info-details">
                                                <br/>
                                                <form className="form-horizontal" role="form">
                                                    <input type="hidden" id="is-new"/>
                                                    <input type="hidden" id="user-id"/>
                                                    <div className="form-group">
                                                        <label htmlFor="firstname" className="col-sm-2 control-label">账号</label>
                                                        <div className="col-sm-10">
                                                            <input
                                                                type="text"
                                                                className="form-control"
                                                                id="user-account"
                                                                placeholder="请输入账户"/>
                                                        </div>
                                                    </div>
                                                    <div className="form-group">
                                                        <label htmlFor="firstname" className="col-sm-2 control-label">昵称</label>
                                                        <div className="col-sm-10">
                                                            <input
                                                                type="text"
                                                                className="form-control"
                                                                id="user-nickname"
                                                                placeholder="请输入昵称"/>
                                                        </div>
                                                    </div>
                                                    <div className="form-group">
                                                        <label htmlFor="firstname" className="col-sm-2 control-label">邮箱</label>
                                                        <div className="col-sm-10">
                                                            <input
                                                                type="text"
                                                                className="form-control"
                                                                id="user-email"
                                                                placeholder="请输入邮箱"/>
                                                        </div>
                                                    </div>
                                                    <div className="form-group">
                                                        <label htmlFor="firstname" className="col-sm-2 control-label">电话</label>
                                                        <div className="col-sm-10">
                                                            <input
                                                                type="text"
                                                                className="form-control"
                                                                id="user-phone"
                                                                placeholder="请输入电话"/>
                                                        </div>
                                                    </div>
                                                    <div className="form-group">
                                                        <label htmlFor="firstname" className="col-sm-2 control-label">密码</label>
                                                        <div className="col-sm-10">
                                                            <input
                                                                type="text"
                                                                className="form-control"
                                                                id="user-password"
                                                                placeholder="请输入密码"/>
                                                        </div>
                                                    </div>
                                                    <div className="form-group">
                                                        <label htmlFor="firstname" className="col-sm-2 control-label">确认密码</label>
                                                        <div className="col-sm-10">
                                                            <input
                                                                type="text"
                                                                className="form-control"
                                                                id="user-sure-password"
                                                                placeholder="请再次输入密码"/>
                                                        </div>
                                                    </div>
                                                    <div className="checkbox input-lg">
                                                        <label >
                                                            <input id="random-password" type="checkbox"/>使用随机密码
                                                        </label>
                                                    </div>
                                                    <div className="checkbox input-lg">
                                                        <label >
                                                            <input id="active-mail" type="checkbox"/>发送激活邮件
                                                        </label>
                                                    </div>
                                                </form>
                                            </div>
                                            <div className="tab-pane fade" id="user-role">
                                                {this.getRoles()}
                                            </div>
                                        </div>
                                    </div>
                                    <div className="modal-footer">
                                        <button type="button" className="btn btn-default" data-dismiss="modal">关闭</button>
                                        <button type="button" className="btn btn-primary" id="user-info-submit">提交更改</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div
                            className="modal fade"
                            id="user-permission"
                            tabIndex="-1"
                            role="dialog"
                            aria-labelledby="myModalLabel"
                            aria-hidden="true">
                            <div className="modal-dialog">
                                <div className="modal-content">
                                    <div className="modal-header">
                                        <button type="button" className="close" data-dismiss="modal" aria-hidden="true">×</button>
                                        <h4 className="modal-title" id="myModalLabel">用户权限设置</h4>
                                    </div>
                                    <div className="modal-body">
                                        <input type="hidden" id="user-permission-employeeid"/>
                                        <div>
                                            <ul id="treeDemo" className="ztree"></ul>
                                        </div>
                                    </div>
                                    <div className="modal-footer">
                                        <button type="button" className="btn btn-default" data-dismiss="modal">关闭</button>
                                        <button type="button" className="btn btn-primary" id="user-Permission-submit">提交更改</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div
                            className="modal fade"
                            id="user-delete"
                            tabIndex="-1"
                            role="dialog"
                            aria-labelledby="myModalLabel"
                            aria-hidden="true">
                            <div className="modal-dialog">
                                <div className="modal-content">
                                    <div className="modal-header">
                                        <button type="button" className="close" data-dismiss="modal" aria-hidden="true">×</button>
                                        <h4 className="modal-title" id="myModalLabel">删除用户</h4>
                                    </div>
                                    <div className="modal-body">
                                        <div
                                            style={{
                                            marginLeft: '15%'   
                                        }}>
                                            <input type="hidden" id="user-delete-userid"/>
                                            <h3>您确定要删除<span className="label label-danger" id="user-delete-username">用户名称</span>该用户？</h3>
                                        </div>
                                    </div>
                                    <div className="modal-footer">
                                        <button type="button" className="btn btn-default" data-dismiss="modal">关闭</button>
                                        <button type="button" className="btn btn-primary" id="user-delete-submit">确认删除</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
});
module.exports = UserManagement;